package com.wl.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wl.config.DataSourceKey;
import com.wl.entity.Brand;
import com.wl.entity.dto.PageDTO;
import com.wl.enums.BrandStatusEnum;
import com.wl.mapper.BrandMapper;
import com.wl.service.BrandService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Resource
    private ApplicationContext applicationContext;
    @Override
    public IPage<Brand> page(PageDTO pageDTO, BrandStatusEnum status) {
        AtomicLong atomicLong = new AtomicLong(1852652359142891522L);
        LambdaQueryChainWrapper<Brand> eq = lambdaQuery().eq(Brand::getStatus, status);
        Page<Brand> page = eq.page(Page.of(pageDTO.getPageNum(), pageDTO.getPageSize()));
        page.getRecords().forEach(brand -> brand.setBaseId(atomicLong.getAndDecrement()));
        return page;
    }

    @Override
    public void copy() {
        List<Brand> list = lambdaQuery().list();
        BrandService bean = applicationContext.getBean(BrandService.class);
        bean.batchSaveDs2(list);
    }

    @DataSourceKey("slave")
    @Override
    public void batchSaveDs2(List<Brand> brands) {
        brands.forEach(brand -> brand.setId(null));
        saveBatch(brands);
    }


}
